import 'event_controller.dart';
import 'dart:convert';

import 'package:beautiful_demo/common/beans/ws_bean.dart';
import 'package:beautiful_demo/common/manager/user.dart';
import 'package:beautiful_demo/common/manager/websocket.dart';
import 'package:beautiful_demo/common/res.dart';
import 'package:beautiful_demo/mvc/chat/list/chat_list_bean.dart';
import 'package:beautiful_demo/mvc/chat/list/controller.dart';
import 'package:beautiful_demo/mvc/good/pop/controller.dart';
import 'package:drive/drive.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:keyboard_utils/keyboard_listener.dart' as kl;
import 'package:keyboard_utils/keyboard_utils.dart';

import 'messages_bean.dart';
import 'view.dart';
import 'package:flutter_mvc/flutter_mvc.dart';


///Description:聊天室
///Author:teihideharu
class ChatRoomController extends BaseController {
  ChatRoomPrivateController private;
  ChatRoomEventController event;
  final textMessageController = TextEditingController();

  final listEmoji = <String>[];
  final scrollController = ScrollController(keepScrollOffset: false);
  final FocusNode focusNode = FocusNode();
  final KeyboardUtils _keyboardUtils = KeyboardUtils();
     get keyboardUtils=>_keyboardUtils;
 KeyboardSpecState keyboardState = KeyboardSpecState.None;
  var bottomHeight = 0.0; //底部距离
  int _idKeyboardListener = 12;
     get idKeyboardListener=>_idKeyboardListener;
    set idKeyboardListener(value)=>_idKeyboardListener=value;
 final ChatListController parentController;
  AnimationController animController;
  List<MessagesDataBean> dataList = [];
  bool isMore = true; //是否下一页
  final int chatId;
  final String logo;
  final String nick;

  ChatRoomController(this.parentController, this.chatId, this.nick, this.logo)
      : super(RoomPage());

  @override
  Future push(BuildContext context, {RouteBuilder routeBuilder}) {
    return DDialogUtils.showBottomDialog(context, widget);
  }

  @override
  void initState() {
    super.initState();
    private=ChatRoomPrivateController(this);
    event=ChatRoomEventController(this);
    animController = MvcAnimationController(controller: this);
    _initListener();
    WebSocketManager.instance.sendMold(WsBean.chatOpen, id: chatId);
    WebSocketManager.instance.sendMold(WsBean.chatRead, id: chatId);
    _initEmoji();
  }

  void animBottomHeight(double bottomHeight) {
    final oldBottomHeight = this.bottomHeight;
    final oldScrollY = scrollController.offset;
    final diff = bottomHeight - this.bottomHeight;

    animController.stop();
    animController.addListener(() {
      if(scrollController.positions.isEmpty) return;
      final value = animController.value * diff;

      this.bottomHeight = oldBottomHeight + value;
      double scrollY = oldScrollY + value;
      if (scrollController.position.maxScrollExtent < scrollY) {
        scrollY = scrollController.position.maxScrollExtent;
      } else if (scrollY < 0) {
        scrollY = 0;
      }
      scrollController.jumpTo(scrollY);

      setState();
    });


    animController.animateTo(1.0,
        duration: const Duration(milliseconds: 800),
        curve: Curves.fastLinearToSlowEaseIn);
  }

  @override
  void dispose() {
    super.dispose();
    _keyboardUtils.unsubscribeListener(subscribingId: _idKeyboardListener);
    WebSocketManager.instance
        .removeListener(WsBean.chat, id: chatId.toString());
    WebSocketManager.instance
        .removeListener(WsBean.chatOpen, id: chatId.toString());
  }

  void _initListener() =>private.initListener();


  //跳转到最底部
  void jumpToBottom(bool isAction) {
    final scrollY = scrollController.offset;
    //判断当前在最低底部，刷新数据之后跳转到底部
    if (isAction ||
        scrollY > scrollController.position.maxScrollExtent - 30.dp) {
      WidgetsBinding.instance.addPostFrameCallback((value){
        scrollController.animateTo(scrollController.position.maxScrollExtent,
            duration: const Duration(milliseconds: 1200),
            curve: Curves.fastLinearToSlowEaseIn);
      });
    }
  }

  void onEmojiClick() =>event.onEmojiClick();


  void _initEmoji() =>private.initEmoji();


  bool _isUtf16Surrogate(int value) =>private.isUtf16Surrogate(value,);


  void onEmojiItemClick(String listEmoji) =>event.onEmojiItemClick(listEmoji,);


  void onSendClick() =>event.onSendClick();


  void onMoreClick() =>event.onMoreClick();


  ///插入消息
  ///如果超过四分钟，插入时间消息
  ///否则插入最后一个时间分组消息
  void insertMessage(WsBean bean) {
    final isThis = bean.id != chatId;
    final messageBean = MessagesDataListBean(null)
      ..value = bean.value
      ..userId = isThis ? UserManager.instance.data.id : bean.id
      ..mold = bean.valueMold
      ..receiveId = isThis ? bean.id : UserManager.instance.data.id
      ..isRead = 0
      ..id = 0
      ..createTime = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());
    if (dataList.isNotEmpty) {
      final lastBean = dataList.last.list.last;
      final time = DateTime.now();
      final lastTime =
          DateFormat("yyyy-MM-dd HH:mm:ss").parse(lastBean.createTime);
      final duration = time.difference(lastTime);
      //判断小于4分钟 最后一段时间插入
      if (duration.inDays == 0 &&
          duration.inHours == 0 &&
          duration.inMinutes < 4) {
        dataList.last.list.add(messageBean);

        parentController.inserMessage(chatId, bean.value, false);
        jumpToBottom(isThis);
        setState();
        return;
      }
    }

    //插入时间 插入消息
    final groupMessageBean = MessagesDataBean(null)..list = [messageBean];
    final time = DateFormat("HH:mm").format(DateTime.now());
    if (DateTime.now().hour > 12) {
      groupMessageBean.time = "下午 " + time;
    } else {
      groupMessageBean.time = "上午 " + time;
    }

    parentController.inserMessage(chatId, bean.value, false);
    dataList.add(groupMessageBean);
    jumpToBottom(isThis);
    setState();
  }


  void amimY(double y){
    final tween=Tween(begin: this.y,end:y);
    animController.stop();
    animController.addListener(() {
      this.y=tween.lerp(animController.value);
      // print(y);
      setState();
    });

    animController.animateTo(1.0,duration: const Duration(milliseconds: 800),curve: Curves.fastOutSlowIn);


  }


  var startY=0.0;
  var y=0.0;
  void onHeaderVerticalDownListener(DragDownDetails details) {
    startY=details.globalPosition.dy;
  }
  void onHeaderVerticalEndListener(DragEndDetails details) {
    if(y>100.dp){
      _keyboardUtils.unsubscribeListener(subscribingId: _idKeyboardListener);
      Navigator.of(context).pop();
    }else{
      amimY(0);
    }
  }

  void onHeaderVerticalUpdateListener(DragUpdateDetails details) {
    y=details.globalPosition.dy-startY;
    if(y<0){
      y=0;
    }
    setState();
  }
}

enum KeyboardSpecState { None, Emoji, Other }
